<template>
  <div class="m-pageView">
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true" ref="searchForm">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="标记名称">
                <el-input v-model.trim="searchForm.name" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标记范围">
                <el-select v-model="searchForm.type" placeholder="请选择" clearable>
                  <el-option v-for="label in labelFilters" :label="label.text" :value="parseInt(label.value)"
                             :key="label.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7" class="searchBtns" :offset="5">
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询</el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>信息列表</div>
        <div class="layout-2">
          <el-button type="text" icon="el-icon-plus" @click="createLabel"
                     v-if="buttonAuthority.label && buttonAuthority.label.create">新建
          </el-button>
        </div>
      </div>
      <div class="m-dataList">
        <el-table
          :data="dataList"
          v-loading="dataListLoading"
          element-loading-text="loading..."
          style="width: 100%"
          max-height="500"
          ref="tableList"
          @sort-change="tableSortBy"
        >
          <el-table-column
            prop="type"
            label="标记范围"
            :formatter="formatterLabelType"
            width="120">
          </el-table-column>
          <el-table-column
            prop="name"
            label="标记名称">
            <template slot-scope="scope">
              <el-button type="text" @click="showInfo(scope.row)">{{scope.row.name}}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            width="120">
          </el-table-column>
          <el-table-column
            prop="createTimeStr"
            label="创建时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="updateUser"
            label="更新人"
            width="120">
          </el-table-column>
          <el-table-column
            prop="updateTimeStr"
            label="更新时间"
            sortable="custom"
            min-width="160">
          </el-table-column>
          <el-table-column
            fixed="right"
            v-if="buttonAuthority.label && (buttonAuthority.label.delete || buttonAuthority.label.edit)"
            label="操作"
            align="center"
            width="110">
            <template slot-scope="scope">
              <el-dropdown trigger="click" @command="type => handleOperation(type, scope.row)">
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  size="small">
                  更多操作
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit" v-if="buttonAuthority.label && buttonAuthority.label.edit">编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" v-if="buttonAuthority.label && buttonAuthority.label.delete">删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="m-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes=pagination.pageSizeList
          :current-page=pagination.pageNo
          :page-size=pagination.pageSize
          layout="total, sizes, prev, pager, next"
          :total=pagination.total>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      class="m-dialog"
      @close="closeAddDialog"
      width="600px">
      <el-form :model="labelForm" ref="labelForm" :rules="rules" :inline="true" label-position="left"
               label-width="80px">
        <el-form-item label="标记范围" prop="type">
          <el-select v-model="labelForm.type" placeholder="请选择" clearable :disabled="showDialogType != 'add'">
            <el-option v-for="label in labelFilters" :label="label.text" :value="parseInt(label.value)"
                       :key="label.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标记名称" prop="name">
          <el-input v-model="labelForm.name" placeholder=""
                    :disabled="showDialogType == 'show'"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="labelDesc">
          <el-input type="textarea" v-model="labelForm.labelDesc" :disabled="showDialogType == 'show'"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button v-if="showDialogType != 'show'" type="primary" @click="submitLabel" :loading="addLoading">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import {mapGetters} from "vuex";
  import * as Utils from "@/utils";
  import * as labelAPI from "@/Api/label";
  export default {
    name: "Label",
    data() {
      return {
        searchForm: {
          name: "",
          type: ''
        },
        labelFilters: [
          {text: "真实账号", value: "1"},
          {text: "LEADS", value: "2"},
          {text: "跟进项", value: "3"}
        ],
        dataListLoading:false,
        addLoading: false,
        dataList: [],
        sortInfo: {},
        activeRow: {},
        showDialogType: '',//弹窗类型
        pagination: Utils.commonPagination(),
        dialogVisible: false,
        labelForm: {},
        rules: {
          type: {
            required: true, message: "请选择标记范围", trigger: "blur"
          },
          name: [
            {required: true, message: "请输入标记名称", trigger: "blur"},
            {max: 50, message: "标记名称长度不能超过50个字符", trigger: "blur"},
//            {pattern: /^[a-zA-Z0-9\_\.]+$/, message: "由字母、数字、下划线或小数点组成", trigger: "blur"}
          ]
        },
        ajaxSearchParams:{},
      };
    },
    computed: {
      ...mapGetters(["buttonAuthority"]),
      dialogTitle(){
        if (this.showDialogType == 'edit') {
          return '编辑标记';
        } else if (this.showDialogType == 'show') {
          return '查看标记'
        } else if (this.showDialogType == 'add') {
          return '创建标记'
        }
      }
    },
    created() {
      this.search();
    },
    methods: {
      tableSortBy(data) {
        if (!data.order) {
          return;
        }
        this.sortInfo.orderParam = data.prop;
        this.sortInfo.orderType = data.order.substr(0, data.order.length - 6);
        this.queryData();
      },
      formatterLabelType(row){
        for (let i = 0; i < this.labelFilters.length; i++) {
          if (this.labelFilters[i].value == row.type) {
            return this.labelFilters[i].text
          }

        }
      },
      queryData() {
        this.dataListLoading = true;
        labelAPI.labelQuery(Object.assign({
          pageSize: this.pagination.pageSize,
          pageNo: this.pagination.pageNo
        }, this.ajaxSearchParams, this.sortInfo))
          .then(res => {
            this.dataListLoading = false;
            if (res.code != '0') {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            let resData = res.data;
            this.dataList = resData.data;
            this.pagination.total = resData.total;
          })
          .catch(error => {
            console.log(error);
            this.dataListLoading = false;
          })
      },
      closeAddDialog() {
        this.labelForm = {
          type: "",
          name: "",
          labelDesc: "",
          color: ""
        }
        this.$refs.labelForm.resetFields();
      },
      search() {
        this.ajaxSearchParams = Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryData();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryData();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryData();
      },
      deleteLabel(row) {
        this.$confirm(`确认删除标记${row.name}?`, "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(_ => {
            return labelAPI.labelDelete({
              id: row.id,
              type: row.type
            });
          })
          .then(res => {
            if (res.code != 0) {
              this.$notify({
                title: "温馨提示",
                message: res.msg,
                type: "warning"
              });
              return;
            }
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.queryData();
          })
          .catch(() => {
          });
      },
      handleOperation(type, row) {
        switch (type) {
          case "edit":
            this.activeRow = {
              type: row.type,
              name: row.name,
              id: row.id,
              labelDesc: row.labelDesc,
            };
            this.labelForm = Object.assign({}, this.activeRow);
            this.showDialogType = 'edit';
            this.dialogVisible = true;
            break;
          case "delete":
            this.deleteLabel(row);
            break;
        }
      },
      createLabel() {
        this.showDialogType = 'add';
        this.dialogVisible = true;
      },
      showInfo(row) {
        this.labelForm = {
          type: row.type,
          name: row.name,
          id: row.id,
          labelDesc: row.labelDesc,
        };
        this.showDialogType = 'show';
        this.dialogVisible = true;
      },
      reset() {
        this.searchForm = {
          name: "",
          type: null
        };
      },
      submitLabel() {
        this.$refs.labelForm.validate(flg => {
          if (!flg) {
            return;
          }
          this.addLoading = true;
          let params = {};
          if (this.showDialogType == 'add') {
            let _colorList = ['#D3E9FF', '#FFCDD7', '#FFE4C7', '#D1EEE2'];
            params = this.labelForm
            params.color = _colorList[Math.floor((Math.random() * (_colorList.length - 1)))]
          } else if (this.showDialogType == 'edit') {
            params = Object.assign({}, this.labelForm, Utils.updateFormItemCopy(this.activeRow));
          }
          labelAPI[this.showDialogType == 'edit' ? 'labelEdit' : 'labelCreate'](params)
            .then(res => {
              this.addLoading = false;
              if (res.code != '0') {
                this.$notify.warning({
                  title: '温馨提示',
                  message: res.msg
                })
                return;
              }
              if (this.pagination.pageNo == 1) {
                this.queryData();
              } else {
                this.pagination.pageNo = 1;
              }
              this.dialogVisible = false;
              this.$message.success(`${this.showDialogType == 'edit' ? '修改' : '新建'}成功`)
            })
            .catch(error => {
              this.addLoading = false;
              console.log(error);
            })
        })
      }
    }
  };
</script>

<style scoped lang="scss">
</style>
